import Vue from 'vue'
import VueRouter from 'vue-router'
const Login = () => import('../components/Login')
const Home = () => import('../components/Home')
const WelCome = () => import('../components/WelCome')
const Users = () => import('../components/user/User')
const Rights = () => import('../components/power/Rights')
const Roles = () => import('../components/power/Roles')
const Cart = () => import('../components/goods/Cart')
const Params = () => import('../components/goods/Params')
const List = () => import('../components/goods/List')
const Add = () => import('../components/goods/children/Add')
const Order = () => import('../components/order/Order')
const Reports = () => import('../components/report/Report')

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: Login,
    meta: {
      title: '登录'
    }
  },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        component: WelCome,
        meta: {
          title: '欢迎'
        }
      },
      {
        path: '/users',
        component: Users,
        meta: {
          title: '用户列表'
        }
      },
      {
        path: '/rights',
        component: Rights,
        meta: {
          title: '权限管理'
        }
      },
      {
        path: '/roles',
        component: Roles,
        meta: {
          title: '角色管理'
        }
      },
      {
        path: '/categories',
        component: Cart,
        meta: {
          title: '商品分类'
        }
      },
      {
        path: '/params',
        component: Params,
        meta: {
          title: '商品参数'
        }
      },
      {
        path: '/goods',
        component: List,
        meta: {
          title: '商品列表'
        }
      },
      {
        path: '/goods/add',
        component: Add,
        meta: {
          title: '添加商品'
        }
      },
      {
        path: '/orders',
        component: Order,
        meta: {
          title: '订单列表'
        }
      },
      {
        path: '/reports',
        component: Reports,
        meta: {
          title: '数据报表'
        }
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 路由导航守卫
router.beforeEach((to, from, next) => {
  document.title = to.meta.title || '电商后台管理系统'
  // 用户访问登录页直接放行
  // next是一个函数  代表放行
  if (to.path === '/login') return next()

  // 获取token值
  const tokenStr = window.sessionStorage.getItem('token')

  // 没有token之间跳转到登录页面
  if (!tokenStr) return next('/login')
  next()
})

export default router
